//package org.jeecg.modules.purchase.task;
//
//import com.alibaba.fastjson.JSON;
//import lombok.extern.slf4j.Slf4j;
//import org.jeecg.common.util.DateUtils;
//import org.jeecg.modules.bid.entity.Bid;
//import org.jeecg.modules.bid.service.IBidService;
//import org.jeecg.modules.message.WebSocket.WebSocketServer;
//import org.jeecg.modules.message.entity.ProcurementMessage;
//import org.jeecg.modules.message.service.IProcurementMessageService;
//import org.jeecg.modules.purchase.entity.PurchasePlan;
//import org.jeecg.modules.purchase.service.IPurchasePlanService;
//import org.jeecg.modules.supplier.service.IProcUserSupplierRelationService;
//import org.springframework.scheduling.annotation.Scheduled;
//import org.springframework.stereotype.Component;
//
//import javax.annotation.Resource;
//import java.time.LocalDateTime;
//import java.util.Arrays;
//import java.util.List;
//import java.util.Map;
//import java.util.stream.Collectors;
//
///**
// * 消息同步定时任务类
// * 用于定时同步消息到客户端
// */
//@Component
//@Slf4j
//public class PurchaseTask {
//
//    @Resource
//    private IPurchasePlanService purchasePlanService;
//
//    @Resource
//    private IProcUserSupplierRelationService procUserSupplierRelationService;
//
//    @Resource
//    private IBidService bidService;
//    /**
//     * 每15秒同步一次采购项目状态
//     * 0 0/30 * * * ? 表示每15秒执行一次
//     */
//    @Scheduled(cron = " 0/15 * * * * ?")
//    public void PurchaseStatusUpdateTask() {
//        List<PurchasePlan> purchasePlans = purchasePlanService.list();
//        for (PurchasePlan purchasePlan : purchasePlans) {
//            if (!purchasePlans.isEmpty()) {
//                    if (purchasePlan.getStatus().equals("1")) {
//                        if(!purchasePlan.getPublishedStatus().equals("1")) {
//                            if (purchasePlan.getAnnouncementEndTime().isBefore(LocalDateTime.now())) {
//                                purchasePlan.setPublishedStatus("1");
//                                purchasePlanService.updateById(purchasePlan);
//                            }
//                        }
//                }
//            }
//        }
//
//    }
//
//}
package org.jeecg.modules.purchase.task;

import lombok.extern.slf4j.Slf4j;
import org.jeecg.modules.bid.entity.BidManagement;
import org.jeecg.modules.bid.mapper.BidManagementMapper;
import org.jeecg.modules.purchase.entity.PurchasePlan;
import org.jeecg.modules.purchase.mapper.PurchasePlanMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.List;

@Slf4j
@Component
public class PurchaseTask {

    @Autowired
    private PurchasePlanMapper purchasePlanMapper;

    @Autowired
    private BidManagementMapper bidManagementMapper;

    /**
     * 每15秒执行一次，同步采购计划状态到投标管理的 publishedStatus
     * 0/15 * * * * ? 表示每15秒执行一次
     */
    @Scheduled(cron = " 0/15 * * * * ?")
    public void syncPublishedStatus() {
        log.info("开始执行投标状态同步任务...");

        // 查询所有已发布的采购计划（status = '1'）
        List<PurchasePlan> plans = purchasePlanMapper.selectList(
                new com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper<PurchasePlan>()
                        .eq(PurchasePlan::getStatus, "1")
        );

        Date now = new Date();

        for (PurchasePlan plan : plans) {
            // 查找关联的 BidManagement（通过 purchaseId）
            BidManagement bid = bidManagementMapper.selectOne(
                    new com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper<BidManagement>()
                            .eq(BidManagement::getPurchaseId, plan.getId())
            );

            if (bid == null) {
                continue; // 无关联投标记录，跳过
            }
            if(bid.getPublishedStatus()!=null && Integer.parseInt(bid.getPublishedStatus())<6) {
                String newStatus = determinePublishedStatus(plan, now);
                if (!newStatus.equals(bid.getPublishedStatus())) {
                    bid.setPublishedStatus(newStatus);
                    bidManagementMapper.updateById(bid);
                    log.info("更新投标 {} 的 publishedStatus 为 {}", bid.getId(), newStatus);
                }
            }
        }

        log.info("投标状态同步任务执行完毕。");
    }

    /**
     * 根据采购计划和当前时间，确定应设置的 publishedStatus
     *
     * @return
     */
    private String determinePublishedStatus(PurchasePlan plan, Date now) {
        // 1. 公告阶段（只要 status=1 就至少是公告）
        String status = "1";

        // 2. 报名阶段：公告截止时间已过
        if (plan.getAnnouncementEndTime() != null && !now.before(plan.getAnnouncementEndTime())) {
            status = "2";
        }

        // 3. 投标阶段：报名截止时间已过
        if (plan.getRegistrationEndTime() != null && !now.before(plan.getRegistrationEndTime())) {
            status = "3";
        }

        // 4. 开标阶段：投标截止时间已过
        if (plan.getBiddingEndTime() != null && !now.before(plan.getBiddingEndTime())) {
            status = "4";
        }

        // 5. 评标阶段：开标时间已过
        if (plan.getOpeningTime() != null && !now.before(plan.getOpeningTime())) {
            status = "5";
        }

        // 6 & 7. 中标 or 流标：评标时间已过
        if (plan.getEvaluationTime() != null && !now.before(plan.getEvaluationTime())) {
            // 判断是否有中标时间 → 有则中标，否则流标
            if (plan.getWinningTime() != null && !now.before(plan.getWinningTime())) {
                status = "6"; // 中标
            } else if (plan.getFlowTime() != null && !now.before(plan.getFlowTime())) {
                status = "7"; // 流标
            }
        }
        return status;
    }
}
